﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.MultiTenancy;

namespace Xms.Abp.BackgroundJob;

[BackgroundJobName("HTTP请求任务", nameof(HttpBackgroundJob))]
public class HttpBackgroundJob: BackgroundJob<HttpBackgroundJobArgs>
{
    protected HttpClient HttpClient { get; }
    protected IBackgroundJobManager BackgroundJobManager { get; }
    protected ICurrentTenant CurrentTenant { get; }

    public HttpBackgroundJob(
        HttpClient httpClient,
        IBackgroundJobManager backgroundJobManager,
        ICurrentTenant currentTenant)
    {
        HttpClient = httpClient;
        BackgroundJobManager = backgroundJobManager;
        CurrentTenant = currentTenant;
    }

    public override async Task ExecuteAsync(HttpBackgroundJobArgs args, CancellationToken cancellationToken = default)
    {
        var requestMessage = new HttpRequestMessage
        {
            Method = new HttpMethod(args.RequestMethod),
            RequestUri = new Uri(args.RequestUrl),
            Content = new StringContent(args.RequestContent, Encoding.GetEncoding(args.RequestContentEncoding ?? "utf-8"), args.RequestContentMediaType ?? "application/json")
        };
        foreach (var key in args.RequestHeaders.Keys)
        {
            requestMessage.Headers.Remove(key);
            requestMessage.Headers.Add(key, args.RequestHeaders[key]);
        }
        var responseMessage = await HttpClient.SendAsync(requestMessage);
        if (responseMessage.IsSuccessStatusCode)
        {
            if (args.ResponseCallDllArgs != null)
            {
                var responseText = responseMessage.Content.ReadAsStringAsync();
                var dllArgs = args.ResponseCallDllArgs.Args;
                var dllArgsList = new List<object>
                {
                    responseText,
                };
                if (dllArgs != null && dllArgs.Length > 0)
                {
                    dllArgsList.AddRange(dllArgs);
                }
                args.ResponseCallDllArgs.Args = dllArgsList.ToArray();
                await BackgroundJobManager.EnqueueAsync(args.ResponseCallDllArgs, CurrentTenant.Id, stoppingToken: cancellationToken);
            }
            else if (args.ResponseCallServiceArgs != null)
            {
                var responseText = responseMessage.Content.ReadAsStringAsync();
                var dllArgs = args.ResponseCallServiceArgs.Args;
                var dllArgsList = new List<object>
                {
                    responseText,
                };
                if (dllArgs != null && dllArgs.Length > 0)
                {
                    dllArgsList.AddRange(dllArgs);
                }
                args.ResponseCallServiceArgs.Args = dllArgsList.ToArray();
                await BackgroundJobManager.EnqueueAsync(args.ResponseCallServiceArgs, CurrentTenant.Id, stoppingToken: cancellationToken);
            }
        }
        else
        {
            throw new HttpRequestException(responseMessage.ReasonPhrase);
        }
    }
}
